<template>
    <div style="display: flex">
        <el-form label-width="110px" size="small" style="flex: 1">
            <el-col class="form-row">
                <el-form-item label="产品代码:">
                    <RiskEntryInput id="fundCode" @set-entry-data="getEntryslist" :returnDatas="instruction.fundCode" />
                </el-form-item>
                <el-form-item label="资产单元编号:" v-show="SHOW_SECURITY">
                    <el-select v-model="instruction.assetCode" size="mini">
                        <el-option
                            v-for="i in computedAssetCodeSelectData"
                            :key="i.assetCode"
                            :label="i.assetCode + ' ' + i.assetName"
                            :value="i.assetCode"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="组合编码:">
                    <el-select
                        name="组合编码"
                        v-model="instruction.fundAccountCode"
                        @change="handleChange(instruction.fundAccountCode, 'fundAccountCode')"
                        size="mini"
                    >
                        <el-option
                            v-for="i in computedFundAccountCodeSelectData"
                            :key="i.fundAccountCode"
                            :label="i.fundAccountCode + ' ' + i.fundAccountName"
                            :value="i.fundAccountCode"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <span slot="label">
                        <span>证券代码</span>
                        <el-popover popper-class="popper" placement="right-start" title="指令类型" width="fit-content" trigger="hover">
                            <span style="margin: 10px 0">{{ instructDescribe }}</span>
                            <span slot="reference" class="label-icon">?</span>
                        </el-popover>
                    </span>

                    <el-select
                        name="证券代码"
                        :key="'exchange'"
                        v-model="instruction.stockCode"
                        @change="handleChange(instruction.stockCode, 'stockCode')"
                        filterable
                        remote
                        :remote-method="getstockCodeList"
                        :loading="stockReportState"
                        size="mini"
                        clearable
                        @clear="handleClearStock"
                    >
                        <el-option
                            v-for="(i, index) in stockReport"
                            :key="i.stockCode + index"
                            :label="i.stockCode + ' ' + i.stockNameSt"
                            :value="i.stockCode"
                            :name="'stockCode' + i.stockCode"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="业务类型:">
                    <el-select
                        name="业务类型"
                        v-model="instruction.businessType"
                        size="mini"
                        @change="handleChange(instruction.businessType, 'businessType')"
                        :disabled="computedBusinessTypeSelectDisabled"
                    >
                        <el-option v-for="i in businessTypeData" :key="i.value" :label="i.label" :value="i.value" :name="'businessType' + i.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="委托方向:">
                    <el-select
                        v-model="instruction.orderDirection"
                        @change="handleChange(instruction.orderDirection, 'orderDirection')"
                        size="mini"
                        :class="['font-color-' + textColor]"
                    >
                        <el-option
                            v-for="i in orderDirectionData"
                            :key="i.dictKey"
                            :label="' ' + i.dictKeyName"
                            :value="i.dictKey"
                            :style="handleTextColor(i.dictKey)"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="目标类型:" v-if="!SHOW_SECURITY || (SHOW_SECURITY && [8].includes(showType)) || (showType == 1 && hkStock)">
                    <el-select
                        name="目标类型"
                        v-model="instruction.targetType"
                        size="mini"
                        :disabled="showType == 6 || instruction.businessType === 'I'"
                        @change="handleChange(instruction.targetType, 'targetType')"
                    >
                        <el-option v-for="(value, key) in targetTypePojo" :key="key" :label="value" :value="key" :name="'targetType' + key">
                        </el-option>
                    </el-select>
                </el-form-item>

                <div v-if="instruction.businessType === 'I'">
                    <el-form-item label="到期收益率:">
                        <RiskInputNumber
                            :input="instruction.yield"
                            :field="'yield'"
                            :inputAfter="'%'"
                            :colorStyle="textColor"
                            :precision="2"
                            :maxlength="15"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                </div>
            </el-col>
        </el-form>
        <el-form label-width="110px" size="small" style="flex: 1">
            <!-- <el-form label-width="110px" size="small"> -->
            <el-col class="form-row">
                <StockForm
                    v-if="showType == 1"
                    :key="formKey"
                    :hkStock="hkStock"
                    :buyStock="buyStock"
                    :cnyExchangeRate="cnyExchangeRate"
                    :stockCode="instruction.stockCode"
                    :stockInfo="stockInfo"
                    @getForm="getForm(arguments)"
                    :formDetail="form"
                    :textColor="textColor"
                    :changeFlag="changeFlag"
                    :notMesh="notMesh"
                    :targetType="instruction.targetType"
                    :refreshNumber="refreshNumber"
                    :protectivePrice="protectivePrice"
                />
                <RefinanceForm
                    v-if="showType == 2"
                    :key="formKey"
                    :stockCode="instruction.stockCode"
                    :stockInfo="stockInfo"
                    @getForm="getForm(arguments)"
                    :formDetail="form"
                />
                <BondForm
                    v-if="showType == 3"
                    :key="formKey"
                    :stockCode="instruction.stockCode"
                    :orderDirection="instruction.orderDirection"
                    :buyBond="buyBond"
                    :isNetPrice="isNetPrice"
                    @getForm="getForm(arguments)"
                    :formDetail="form"
                    :textColor="textColor"
                    :changeFlag="changeFlag"
                    :notMesh="notMesh"
                    :stockInfo="stockInfo"
                    :targetType="instruction.targetType"
                    :refreshNumber="refreshNumber"
                />
                <FundForm
                    v-if="showType == 4"
                    :key="formKey"
                    :stockCode="instruction.stockCode"
                    @getForm="getForm(arguments)"
                    :formDetail="form"
                    :textColor="textColor"
                    :changeFlag="changeFlag"
                    :notMesh="notMesh"
                    :stockInfo="stockInfo"
                    :targetType="instruction.targetType"
                    :refreshNumber="refreshNumber"
                />
                <WarrantForm
                    v-if="showType == 5"
                    :key="formKey"
                    :stockCode="instruction.stockCode"
                    :stockInfo="stockInfo"
                    @getForm="getForm(arguments)"
                    :formDetail="form"
                    :textColor="textColor"
                    :changeFlag="changeFlag"
                    :targetType="instruction.targetType"
                    :refreshNumber="refreshNumber"
                />
                <BuyBackForm
                    v-if="showType == 6"
                    :stockCode="instruction.stockCode"
                    :stockInfo="stockInfo"
                    @getForm="getForm(arguments)"
                    :formDetail="form"
                    :textColor="textColor"
                    :targetType="instruction.targetType"
                    :refreshNumber="refreshNumber"
                />

                <SHFixedForm
                    v-if="showType == 8"
                    :stockInfo="stockInfo"
                    @getForm="getForm(arguments)"
                    :formDetail="form"
                    :textColor="textColor"
                    :changeFlag="changeFlag"
                    :targetType="instruction.targetType"
                />

                <el-form-item v-if="instruction.businessType === 'I'" label="交易对手:">
                    <el-select
                        name="交易对手"
                        v-model="instruction.opponentCode"
                        @change="handleChange(instruction.opponentCode, 'opponentCode')"
                        filterable
                        clearable
                        :filter-method="getOpponentCode"
                        :loading="selectLoading"
                        @visible-change="handleOpponentVisibleChange"
                        size="mini"
                    >
                        <el-option
                            v-for="i in opponentCodeSelectData"
                            :key="i.dictKey"
                            :label="i.dictKey + ' ' + i.dictKeyName"
                            :value="i.dictKey"
                            :name="'opponentCode' + i.dictKey"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="目标类型:" v-if="SHOW_SECURITY && ([2, 3, 4, 5, 6].includes(showType) || (showType == 1 && !hkStock))">
                    <el-select
                        name="目标类型"
                        v-model="instruction.targetType"
                        size="mini"
                        :disabled="showType == 6 || instruction.businessType === 'I'"
                    >
                        <el-option v-for="(value, key) in targetTypePojo" :key="key" :label="value" :value="key" :name="'targetType' + key">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-form>
        <!-- </el-form> -->
    </div>
</template>

<script lang="ts">
import { getCNYExRateByCodeAsync, getStockReportSelect } from '@/common/dict/dict';
import Invest from '@/common/dict/invest';
import DictionConstUtil, { objToArr, SGU_CACHE } from '@/utils/diction-const-util';
import { getConfigItem, handleTextColor, highlightColor, uniqueFunc } from '@/utils/tools';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import StockForm from './exchangeOrder/stock-form.vue';
import RefinanceForm from './exchangeOrder/refinance-form.vue';
import BondForm from './exchangeOrder/bond-form.vue';
import FundForm from './exchangeOrder/fund-form.vue';
import WarrantForm from './exchangeOrder/warrant-form.vue';
import BuyBackForm from './exchangeOrder/buy-back-form.vue';
import { getBusinessType } from '@/pages/risk-time/api';
import { Dictionary } from '@/pages/risk-time/types/Dictionary';
import { SelectOptionItemData } from '@/pages/risk-time/types/SelectOptionItemData';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import SHFixedForm from './exchangeOrder/sh-fixed-form.vue';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';

@Component({
    name: 'ExchangeOrder',
    components: {
        StockForm,
        RefinanceForm,
        BondForm,
        FundForm,
        WarrantForm,
        BuyBackForm,
        SHFixedForm,
        RiskEntryInput,
        RiskInputNumber,
    },
})

// 交易所指令
export default class ExchangeOrder extends Vue {
    @Prop()
    detail: any;
    @Prop()
    stockInfoCache: any;
    @Prop()
    renderCount: number;
    @Prop()
    notMesh: boolean; // 非风险试算页面
    @Prop()
    isBSE: boolean; // 是否北交所业务
    @Prop()
    refreshNumber: number; // 刷新市价
    Invest: any = new Invest();
    handleTextColor = handleTextColor;
    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据

    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据
    allStockType: any[] = [];
    allOrderDirection: any[] = [];
    orderDirectionSelectData: any[] = []; // 订单方向下拉框数据
    investPriceSelectData: any[] = []; // 价格模式下拉框数据
    // stockCodeSelectData: any[] = []; // 证券代码下拉框数据
    //  stockBusinessTypes: any[] = []; // 股票指令业务类型
    defaultStockBusinessTypes: SelectOptionItemData[] = [
        {
            label: '交易所业务',
            value: '1',
        },
    ];
    businessTypeData: SelectOptionItemData[] = [];

    private instruction: any = {
        fundCode: '', // 产品代码
        fundAccountCode: '', // 组合编码
        reportCode: '', // 申报代码
        businessType: '1',
        orderDirection: '', // 委托方向
        stockCode: '',
        fundNameSt: '',
        fundAccountName: '',
        targetType: '1',
        assetCode: '',
        assetName: '',
    };

    stockReport: any[] = []; // 证券代码下拉
    stockReportState: boolean = false;
    orderDirectionData: any[] = []; // 委托方向数据

    showType: number = 1;
    stockValues = {
        // businessType: '', // 业务类型
        orderPrice: '', // 指令价格
        orderAmount: '', // 指令数量
        orderBalance: '', // 指令金额
        winningRate: '', // 预估中签率
        orderPriceType: '2', // 价格模式
    };
    hkStock: boolean = false; // 是否港股股票
    buyStock: boolean = false; // 是否申购股票
    cnyExchangeRate: string = ''; // 转成人民币的汇率

    // 转融通指令额外表单数据
    refinanceValues = {
        // businessType: '', // 业务类型
        deadline: '', // 期限
        rate: '', // 费率
        orderAmount: '', // 融出数量
        opponentCode: '', // 交易对手
    };

    // 债券指令额外表单数据
    bondValues = {
        // businessType: '', // 业务类型
        netPrice: '', // 净价
        orderAmount: '', // 指令数量
        netMoney: '', // 指令金额
        allPrice: '', // 全价价格
        allAmount: '', // 全价数量
        allMoney: '', // 全价金额
        winningRate: '', // 预估中签率
        orderPriceType: '2', // 价格模式
    };
    buyBond: boolean = false; // 是否债券申购
    isNetPrice: boolean = false; // 是否净价

    // 基金指令额外表单数据
    fundValues = {
        // businessType: '', // 业务类型
        orderPrice: '', // 指令价格
        orderAmount: '', // 指令数量
        orderBalance: '', // 指令金额
        orderPriceType: '2', // 价格模式
    };

    // 权证指令额外表单数据
    warrantValues = {
        // businessType: '', // 业务类型
        orderPrice: '', // 指令价格
        orderAmount: '', // 指令数量
        orderBalance: '', // 指令金额
    };

    // 回购指令额外表单数据
    buyBackValues = {
        // businessType: '', // 业务类型
        orderRate: '',
        orderBalance: '', // 指令金额
        orderPriceType: '2', // 价格模式
    };

    // 上交所固收指令表单
    shFixedValues = {
        orderPrice: '', // 净价价格
        orderAmount: '', // 指令数量
        orderBalance: '', // 净价金额
        totalInterest: '', // 总应计利息
        fullPrice: '',
        fullBalance: '',
    };
    fundInfo: any = {};
    stockInfo: any = {};
    // renderCount: number = 0;
    instructDescribe: string = '选择完证券代码显示对应的指令类型';
    securityloanType: string = '';
    form: any = {}; // 子组件表单
    tradeDirections: any[] = [];
    formName: any = {};
    fundAccounts: any[] = [];
    formCache: any = {};
    // 委托方向对应业务类型数据
    innerOrderDirectionData: any[] = [];
    formKey: number = 0;
    textColor: string = '';
    opponentCodeSelectData: any[] = [];

    stockCodeUrl: string = '';
    targetTypePojo: any = {}; // 目标类型枚举
    changeFlag: string = ''; // 证券变动方向

    // 指令信息回显
    @Watch('renderCount', { immediate: true, deep: true })
    async setForm() {
        console.log(this.detail, 'this.detail', this.isBSE);

        if (this.detail && Object.keys(this.detail).length) {
            let instruction = this.detail;
            // 获取组合编码下拉框数据
            let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
            arr.forEach(item => {
                this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
            });
            if (instruction.stockCode) {
                let reportCode = instruction.stockCode.split(' ');
                instruction.reportCode = reportCode[0];
            }
            this.stockReportState = true;
            let res: any = await new Promise((resolve, reject) => {
                this.$axios
                    .post(this.stockCodeUrl, {
                        dictKey: instruction.reportCode,
                        dictKeyName: instruction.reportCode,
                    })
                    .then((res: any) => {
                        resolve(res);
                    })
                    .catch(err => {
                        reject(err);
                    });
            });
            if (res) {
                this.stockReport = res;
                this.stockInfo = this.stockReport.find(item => item.stockCode === instruction.stockCode);
                this.fundInfo = this.fundCodeSelectData.find(item => item.fundCode === instruction.fundCode) || {};
                if (this.isBSE) {
                    this.$emit('getStockInfo', this.stockInfo, '11');
                } else {
                    this.$emit('getStockInfo', this.stockInfo, '6');
                }
                // if (this.detail.instNo) {
                if (this.stockInfo?.marketCode && this.stockInfo?.stockType) {
                    this.handleStockBusinessType(this.stockInfo, this.stockInfo.marketCode, this.stockInfo.stockType, false);
                }
                // }
                this.settingValues(instruction);
                this.stockReportState = false;
            } else {
                this.stockReportState = false;
            }
            // this.settingValues(instruction);
        } else {
            this.resetValues();
            // this.getstockCodeList('');
            this.businessTypeData = this.defaultStockBusinessTypes;
        }
    }

    /**
     * 判断字段颜色
     */
    @Watch('instruction', { immediate: true, deep: true })
    handleFieldColor() {
        if (['1', '3', '5', 'U', 'P'].includes(this.instruction.orderDirection)) {
            this.textColor = highlightColor()[1];
        } else if (['2', '4', '6', 'T', 'Q', '9', 'A', 'B'].includes(this.instruction.orderDirection)) {
            this.textColor = highlightColor()[2];
        } else {
            this.textColor = highlightColor()[0];
        }
    }
    // 科创板保护价
    private protectivePrice: any = null;

    @Watch('stockInfo', { immediate: true, deep: true })
    watchStockInfo() {
        // 根据订单参数获取科创板保护机制的金额
        if (['0', '1', '2'].includes(this.stockInfo.stockProperty) && this.stockValues.orderPriceType === '2') {
            let data = {
                fundCode: this.instruction.fundCode,
                orderAmount: this.stockValues.orderAmount,
                orderBalance: this.stockValues.orderBalance,
                orderDirection: this.instruction.orderDirection,
                orderPrice: this.stockValues.orderPrice,
                orderPriceType: this.stockValues.orderPriceType,
                stockCode: this.instruction.stockCode,
                storkProperty: this.stockInfo.stockProperty,
                stockType: this.stockInfo.stockType,

                targetType: this.instruction.targetType,
            };
            if (this.verifyObjEmpty(data)) {
                this.$axios({ method: 'post', url: '/systemParam/getProtectInformation', data }).then((res: any) => {
                    console.log(res);
                    this.protectivePrice = res;
                });
            } else {
                this.protectivePrice = null;
            }
        }
    }

    @Watch('stockValues', { immediate: true, deep: true })
    watchStockValues(newData, oldData) {
        // 根据订单参数获取科创板保护机制的金额
        if (['0', '1', '2'].includes(this.stockInfo.stockProperty) && this.stockValues.orderPriceType === '2') {
            let data = {
                fundCode: this.instruction.fundCode,
                orderAmount: this.stockValues.orderAmount,
                orderBalance: this.stockValues.orderBalance,
                orderDirection: this.instruction.orderDirection,
                orderPrice: this.stockValues.orderPrice,
                orderPriceType: this.stockValues.orderPriceType,
                stockCode: this.instruction.stockCode,
                storkProperty: this.stockInfo.stockProperty,
                stockType: this.stockInfo.stockType,
                targetType: this.instruction.targetType,
            };
            if (this.verifyObjEmpty(data)) {
                if (JSON.stringify(newData) != JSON.stringify(oldData)) {
                    this.$axios({ method: 'post', url: '/systemParam/getProtectInformation', data }).then((res: any) => {
                        this.protectivePrice = res;
                    });
                }
            } else {
                this.protectivePrice = null;
            }
        }
    }

    // 校验对象内每个key都有值
    private verifyObjEmpty(form: any) {
        let flag = true;
        for (let key in form) {
            if (!form[key]) {
                return false;
            }
        }
        return flag;
    }

    @Watch('showType', { immediate: true, deep: true })
    onWatchShowType() {
        this.formKey++;
    }

    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');
    // 监听 资产单元计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedAssetCodeSelectData', { immediate: true, deep: true })
    watchcomputedAssetCode(newData) {
        if (!this.SHOW_SECURITY) {
            return;
        }
        let obj: any = {};
        if (newData && newData.length) {
            const d1 = newData.find(item => item.assetCode == this.instruction.assetCode);
            obj = d1 || newData[0];
        }
        this.instruction.assetCode = obj.assetCode;
        this.instruction.assetName = obj.assetName;
    }

    // 监听 组合编码计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedFundAccountCodeSelectData', { immediate: true, deep: true })
    watchcomputedFundAccountCode(newData) {
        let obj: any = {};
        if (newData && newData.length) {
            const d1 = newData.find(item => item.fundAccountCode == this.instruction.fundAccountCode);
            obj = d1 || newData[0];
        }
        this.instruction.assetCode = obj.assetCode;
        this.instruction.assetName = obj.assetName;
        this.instruction.fundAccountCode = obj.fundAccountCode;
        this.instruction.fundAccountName = obj.fundAccountName;
        let form: any = {};
        if (!Object.keys(this.form).length) {
            form = JSON.parse(JSON.stringify(this.formCache));
        } else {
            form = JSON.parse(JSON.stringify(this.form));
        }

        if (this.isBSE) {
            this.$emit('handleSettingValue', { ...this.instruction, ...form, showType: this.showType }, '11');
        } else {
            this.$emit('handleSettingValue', { ...this.instruction, ...form, showType: this.showType }, '6');
        }
    }

    get computedAssetCodeSelectData(): any {
        return uniqueFunc(this.fundAccountCodeSelectData[this.instruction.fundCode], 'assetCode');
    }

    // 组合编码下拉框计算属性;
    get computedFundAccountCodeSelectData() {
        let data = this.fundAccountCodeSelectData[this.instruction.fundCode];
        let retData = [];
        if (data && this.SHOW_SECURITY) {
            const obj = data.filter(item => item.assetCode == this.instruction.assetCode);
            retData = obj || [];
        } else {
            retData = data;
        }
        return retData;
    }

    async mounted() {
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);
        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
        // 获取价格模式下拉框数据
        this.investPriceSelectData = await SGU_CACHE('PriceType', '/dict/list/code/Y_000237', []);
        // 获取证券代码下拉框数据
        this.getstockCodeList('');
        // 获取所有证券类别 (用于筛选订单方向)
        this.allStockType = await SGU_CACHE('StockType', '/dict/stockType/list', []);
        // 获取所有订单方向
        this.allOrderDirection = await SGU_CACHE('TradeDirection', '/dict/tradeDirections', []);
        this.businessTypeData = this.defaultStockBusinessTypes;
        // 获取目标类型
        this.targetTypePojo = DictionConstUtil.targetType;
    }

    // 根据委托方向动态设置业务类型是否禁用
    get computedBusinessTypeSelectDisabled() {
        this.stockCodeUrl = '/dict/stock/report/select/1';
        // 判断组件使用是否是在风险试算页面
        if (this.notMesh) {
            // 单独的交易所指令页面，委托方向为9-配股认购、T-提交质押、U-转回质押时业务类型不可编辑
            if (['9', 'T', 'U', 'A', 'B'].includes(this.instruction.orderDirection)) {
                return true;
            } else {
                return false;
            }
        } else if (this.isBSE) {
            this.stockCodeUrl = '/dict/stock/report/select/9';
            return true;
        } else {
            return false;
        }
    }

    // 根据是否北交所业务获取不同的证券代码请求路径
    get computedStockCodeUrl() {
        if (this.isBSE) {
            this.stockCodeUrl = '/dict/stock/report/select/9';
        } else {
            this.stockCodeUrl = '/dict/stock/report/select/1';
        }
        return this.stockCodeUrl;
    }

    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        this.instruction[field] = value;
        if (this.isBSE) {
            this.$emit('handleSettingValue', { ...this.instruction, showType: this.showType }, '11');
        } else {
            this.$emit('handleSettingValue', { ...this.instruction, ...this.shFixedValues, showType: this.showType }, '6');
        }
        // this.$emit('handleSettingValue', { ...this.instruction, ...this.shFixedValues, showType: this.showType }, '6');
    }

    // 获取子表单
    getForm(args: any) {
        console.log(args, 'args');

        this.formCache = JSON.parse(JSON.stringify(args[0]));
        // let types = ['stockValues', 'refinanceValues', 'bondValues', 'fundValues', 'warrantValues', 'buyBackValues', 'shFixedValues'];
        this[args[1]] = args[0];
        // this.$emit('handleSettingValue', { ...this.instruction, ...this[args[1]], showType: this.showType }, '6');
        if (this.isBSE) {
            this.$emit('handleSettingValue', { ...this.instruction, ...this[args[1]], showType: this.showType }, '11');
        } else {
            this.$emit('handleSettingValue', { ...this.instruction, ...this[args[1]], showType: this.showType }, '6');
        }
    }

    // 参数变动
    async handleChange(value, field) {
        if (field === 'fundCode') {
            this.handleFundCodeChange(value);
        } else if (field === 'fundAccountCode') {
            this.handleFundAccountCodeChange(value);
        } else if (field === 'stockCode') {
            await this.handleStockCodeChange(value);
        } else if (field === 'orderDirection') {
            this.handleOrderDirectionChange(value);
        } else if (field === 'businessType') {
            this.handleBusinessType(value);
        } else if (field === 'opponentCode') {
            this.getOpponentCode(value);
        }

        let form: any = {};
        if (!Object.keys(this.form).length) {
            form = JSON.parse(JSON.stringify(this.formCache));
        } else {
            form = JSON.parse(JSON.stringify(this.form));
        }
        // form.businessType = this.formCache.businessType;
        // this.$emit('handleSettingValue', { ...this.instruction, ...form, showType: this.showType }, '6');
        if (this.isBSE) {
            this.$emit('handleSettingValue', { ...this.instruction, ...form, showType: this.showType }, '11');
        } else {
            this.$emit('handleSettingValue', { ...this.instruction, ...form, showType: this.showType }, '6');
        }
    }

    getEntryslist(val: any) {
        this.instruction.fundCode = val;
        this.handleChange(val, 'fundCode');
    }

    // 获取交易对手方数据
    getOpponentCode(value: string) {
        this.$axios
            .post('/dict/opponent/select', {
                dictKey: value,
                dictKeyName: value,
            })
            .then((res: any) => {
                this.opponentCodeSelectData = res;
            });
    }

    handleOpponentVisibleChange(val: any) {
        if (!val) {
            this.getOpponentCode('');
        }
    }

    handleFundCodeChange(value: string) {
        let fund = this.fundCodeSelectData.find(item => item.fundCode === value) || {};
        this.fundInfo = fund;
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || [])[0] || {};
        this.instruction.fundNameSt = fund.fundNameSt;
        this.instruction.fundAccountCode = fundAccount.fundAccountCode;
        this.instruction.fundAccountName = fundAccount.fundAccountName;
        this.instruction.assetCode = fundAccount.assetCode;
        this.instruction.assetName = fundAccount.assetName;
        this.handleJudgeShowType();
    }

    handleFundAccountCodeChange(value: string) {
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || []).find(item => item.fundAccountCode === value) || {};
        this.instruction.assetCode = fundAccount.assetCode;
        this.instruction.assetName = fundAccount.assetName;
        this.instruction.fundAccountName = fundAccount.fundAccountName;
    }
    handleOrderDirectionChange(value: string) {
        let a = value.substr(0, 1);
        if (a === 'l' && this.instructDescribe === '股票指令') {
            this.showType = 2;
            this.instructDescribe = '转融通指令';
            this.form.businessType = this.formCache.businessType;
        } else if (this.instructDescribe === '转融通指令' && a !== 'l') {
            this.instructDescribe = '股票指令';
            this.showType = 1;
        }

        let obj = this.orderDirectionData.find(ele => ele.dictKey == value);
        if (obj) {
            this.changeFlag = obj.param2;
        } else {
            this.changeFlag = '';
        }
    }

    handleBusinessType(businessType: string) {
        if (this.instruction.businessType === 'I') {
            this.showType = 8;
            // 获取交易对手方
            this.getOpponentCode('');
            this.$set(this.instruction, 'yield', '');
            this.$set(this.instruction, 'opponentCode', '');
            // 上交所固收指令目标类型默认为绝对数量，因为金额不可编辑（需求3680）
            this.instruction.targetType = '1';
        } else {
            this.showType = 1;
        }

        this.innerOrderDirectionData.filter(ele => {
            if (ele.dictKey == businessType) {
                if (ele['innerDictionary'] && JSON.stringify(ele['innerDictionary']) !== '{}') {
                    this.orderDirectionData = JSON.parse(ele['innerDictionary'] || '[]');
                } else {
                    this.orderDirectionData = [];
                    this.instruction.orderDirection = '';
                }
                if (this.orderDirectionData.length) {
                    this.instruction.orderDirection = this.orderDirectionData[0].dictKey;
                    this.changeFlag = this.orderDirectionData[0].param2;
                } else {
                    this.yh_message_warn('该业务类型无对应的委托方向');
                }
            }
        });
    }

    // 设置指令中的值
    settingValues(instruction) {
        let reportCode = '';
        if (instruction.stockCode) {
            reportCode = instruction.stockCode.split(' ');
        }
        let newInstruction: any = {
            fundCode: instruction.fundCode, // 产品代码
            fundAccountCode: instruction.fundAccountCode || instruction.groupCode, // 组合编码
            reportCode: instruction.reportCode || reportCode[0], // 申报代码
            stockCode: instruction.stockCode,
            // stockCode: this.stockInfo ? this.stockInfo.stockCode : '' || instruction.stockCode, // 证券代码
            orderDirection: instruction.orderDirection, // 委托方向
            fundNameSt: instruction.fundNameSt || instruction.fundName,
            fundAccountName: instruction.fundAccountName || instruction.groupName,
            assetCode: instruction.assetCode,
            assetName: instruction.assetName,
            correspondingIndex: instruction.correspondingIndex,
            orderPriceType: instruction.orderPriceType,
            businessType: instruction.businessType,
            targetType: instruction.targetType,
        };
        this.instruction = newInstruction;

        this.handleJudgeShowType();
        this.handleOrderDirectionChange(instruction.orderDirection);
        // 上交所固收指令
        if (this.instruction.businessType == 'I') {
            this.instruction.yield = instruction.yield;
            this.instruction.opponentCode = instruction.opponentCode;
            instruction.showType = 8;
            this.showType = 8;
            this.getOpponentCode(instruction.opponentCode);
        }
        if (instruction.showType == 1 || this.showType == 1) {
            this.stockValues = {
                // businessType: instruction.businessType, // 业务类型
                orderPrice: instruction.orderPrice, // 指令价格
                orderAmount: instruction.orderAmount, // 指令数量
                orderBalance: instruction.orderBalance, // 指令金额
                winningRate: instruction.winningRate, // 预估中签率
                orderPriceType: instruction.orderPriceType, // 价格模式
            };
            this.form = JSON.parse(JSON.stringify(this.stockValues));
        } else if (instruction.showType == 2 || this.showType == 2) {
            this.refinanceValues = {
                // businessType: instruction.businessType, // 业务类型
                deadline: instruction.deadline, // 期限
                rate: instruction.rate, // 费率
                orderAmount: instruction.orderAmount, // 融出数量
                opponentCode: instruction.opponentCode, // 交易对手
            };

            this.form = JSON.parse(JSON.stringify(this.refinanceValues));
        } else if (instruction.showType == 3 || this.showType == 3) {
            this.bondValues = {
                // businessType: instruction.businessType, // 业务类型
                netPrice: '', // 净价
                orderAmount: instruction.orderAmount, // 指令数量
                netMoney: '', // 指令金额
                allPrice: '', // 全价价格
                allMoney: '', // 全价金额
                allAmount: '', // 全价数量
                winningRate: instruction.winningRate, // 预估中签率
                orderPriceType: instruction.orderPriceType, // 价格模式
            };
            if (this.stockInfo.quoteType === '1') {
                this.bondValues.netPrice = instruction.netPrice || instruction.orderPrice;
                this.bondValues.netMoney = instruction.netMoney || instruction.orderBalance;
            } else {
                this.bondValues.allPrice = instruction.allPrice || instruction.orderPrice;
                this.bondValues.allMoney = instruction.allMoney || instruction.orderBalance;
            }
            this.form = JSON.parse(JSON.stringify(this.bondValues));
        } else if (instruction.showType == 4 || this.showType == 4) {
            this.fundValues = {
                // businessType: instruction.businessType, // 业务类型
                orderPrice: instruction.orderPrice, // 指令价格
                orderAmount: instruction.orderAmount, // 指令数量
                orderBalance: instruction.orderBalance, // 指令金额
                orderPriceType: instruction.orderPriceType, // 价格模式
            };
            this.form = JSON.parse(JSON.stringify(this.fundValues));
        } else if (instruction.showType == 5 || this.showType == 5) {
            this.warrantValues = {
                // businessType: instruction.businessType, // 业务类型
                orderPrice: instruction.orderPrice, // 指令价格
                orderAmount: instruction.orderAmount, // 指令数量
                orderBalance: instruction.orderBalance, // 指令金额
                // orderPriceType: instruction.orderPriceType, // 价格模式
            };
            this.form = JSON.parse(JSON.stringify(this.warrantValues));
        } else if (instruction.showType == 6 || this.showType == 6) {
            this.buyBackValues = {
                // businessType: instruction.businessType, // 业务类型
                orderBalance: instruction.orderBalance, // 指令金额
                orderRate: instruction.orderRate || instruction.orderPrice,
                orderPriceType: instruction.orderPriceType, // 价格模式
            };
            this.form = JSON.parse(JSON.stringify(this.buyBackValues));
        } else if (instruction.showType == 8) {
            this.shFixedValues = {
                orderPrice: instruction.orderPrice, // 净价价格
                orderAmount: instruction.orderAmount, // 指令数量
                orderBalance: instruction.orderBalance, // 净价金额
                totalInterest: instruction.totalInterest, // 总应计利息
                fullPrice: instruction.fullPrice,
                fullBalance: instruction.fullBalance,
            };
            this.form = JSON.parse(JSON.stringify(this.shFixedValues));
        }
    }

    // 获取证券代码下拉框数据
    async getstockCodeList(val: string) {
        console.log(this.computedStockCodeUrl, this.stockCodeUrl, 'jjj');
        this.stockReportState = true;
        await this.$axios
            .post(this.stockCodeUrl, {
                dictKey: val,
                dictKeyName: val,
            })
            .then((res: any) => {
                this.stockReport = res;
                this.stockReportState = false;
            });
    }

    // 证券代码选择变动事件
    async handleStockCodeChange(value: string) {
        this.resetValues();
        if (value) {
            this.stockInfo = this.stockReport.find(item => item.stockCode === value);
            // this.stockInfo = this.stockReport.find((item) => item.reportCode === value);
            if (this.isBSE) {
                this.$emit('getStockInfo', this.stockInfo, '11');
            } else {
                this.$emit('getStockInfo', this.stockInfo, '6');
            }
            this.instruction.reportCode = this.stockInfo.reportCode;
            this.instruction.stockCode = this.stockInfo.stockCode;
            this.handleJudgeShowType();
            if (this.stockInfo.marketCode && this.stockInfo.stockType) {
                await this.handleStockBusinessType(this.stockInfo, this.stockInfo.marketCode, this.stockInfo.stockType, true);
            }
        }
    }

    // 证券代码清除事件
    handleClearStock() {
        this.innerOrderDirectionData = [];
        this.orderDirectionData = [];
        this.businessTypeData = this.defaultStockBusinessTypes;
        this.getstockCodeList('');
        this.stockInfo = null;
        this.resetValues();
        this.showType = 1;
        this.instructDescribe = '选择完证券代码显示对应的指令类型';
    }

    /**
     * 用于选择证券代码后，判断展示类型
     */
    handleJudgeShowType() {
        // 1.资产分类为股票或者证券类别为存托凭证申购、股票申购、增发、配售、配股、优先股转股
        // 2.交易场所：上交所、深交所、港交所、港股通（沪）、港股通（深）
        if (!this.stockInfo) {
            this.showType = 1;
            return;
        }
        if (this.instruction.orderDirection === 'I') {
            this.showType = 8;
            return;
        }
        if (
            (this.stockInfo.categoryCode === 'GP' || ['23', 'a', 'd', 'f', 'h', '<'].includes(this.stockInfo.stockType)) &&
            ['1', '2', 'H', 'n', 'o'].includes(this.stockInfo.marketCode)
        ) {
            let buyStock = this.stockInfo.stockType === 'a';
            // let hkStock = ['n', 'o'].includes(this.stockInfo.marketCode)
            let cnyExchangeRate = '1';
            let hkStock = false;
            if (this.stockInfo.curCode === 'HK1' || this.stockInfo.curCode === 'HK2' || this.stockInfo.curCode === 'HKD') {
                // cnyExchangeRate = getCNYExRateByCodeAsync(this.stockInfo.stockCode);

                this.$axios.get('/dict/query/stock/CNYExRate/' + this.stockInfo.stockCode + '/' + (this.fundInfo.setNo || 0)).then((res: any) => {
                    this.cnyExchangeRate = res;
                });
                hkStock = true;
            }
            this.instructDescribe = '股票指令';
            this.hkStock = hkStock;
            this.buyStock = buyStock;
            // this.cnyExchangeRate = cnyExchangeRate;
            this.showType = 1;
        } else if (
            (this.stockInfo.categoryCode === 'ZQ' || ['n', 'B', 'C', 'k', 'y'].includes(this.stockInfo.stockType)) &&
            ['1', '2'].includes(this.stockInfo.marketCode) &&
            this.instruction.businessType !== 'I'
        ) {
            // 5.资产分类为债券或者证券类别为债券增发、债转股、配债、债券申购、债回售
            // 6.交易场所：上交所、深交所
            let buyBond = this.stockInfo.stockType === 'k';
            let isNetPrice = false;
            if (this.stockInfo.quoteType) {
                isNetPrice = this.stockInfo.quoteType === '1';
            }
            this.instructDescribe = '债券指令';
            this.showType = 3;
            this.buyBond = buyBond;
            this.isNetPrice = isNetPrice;
        } else if (
            (this.stockInfo.categoryCode === 'JJ' || ['2', 'F'].includes(this.stockInfo.stockType)) &&
            ['1', '2'].includes(this.stockInfo.marketCode)
        ) {
            // 1.证券代码所属资产分类为基金
            // 2.交易场所：上交所、深交所 证券类别等于封闭式基金、开放式基金
            this.instructDescribe = '基金指令';
            this.showType = 4;
        } else if (this.stockInfo.categoryCode === 'QZ' && ['1', '2'].includes(this.stockInfo.marketCode)) {
            // 1.资产分类为权证
            // 2.交易场所：上交所、深交所
            this.instructDescribe = '权证指令';
            this.showType = 5;
        } else if (this.stockInfo.categoryCode === 'HG' && ['1', '2'].includes(this.stockInfo.marketCode)) {
            // 1.资产分类为回购
            // 2.交易场所：上交所、深交所
            this.instructDescribe = '回购指令';
            this.showType = 6;
            this.instruction.targetType = '2';
        }
        // else if(['1','V','F'].includes(stockInfo.stockType) && ['1','2'].includes(stockInfo.marketCode)){
        //     this.name.instructDescribe = '股票指令'
        //     this.name.securityloanType = '转融通'
        // }
    }

    // 根据证券信息获取业务类型
    async handleStockBusinessType(stockInfo, marketCode, stockType, type) {
        // let res = await getBusinessType(marketCode, stockType);
        let res: any = await new Promise((resolve, reject) => {
            // this.$axios
            // .get('/dict/businessType/' + marketCode + '/' + stockType + '?stockCode=' + stockInfo.reportCode + '+' + stockInfo.marketChar)
            this.$axios
                .post('/dict/businessType', { marketCode, stockType, stockCode: stockInfo.reportCode + '+' + stockInfo.marketChar })
                .then((response: any) => {
                    resolve(response);
                })
                .catch((err: any) => {
                    reject(err);
                });
        });
        if (res && res.length > 0) {
            this.businessTypeData = res.map(
                item =>
                    ({
                        label: item.dictKeyName,
                        value: item.dictKey,
                    } as SelectOptionItemData)
            );
            this.innerOrderDirectionData = res;
            if (this.notMesh) {
                this.businessTypeData = this.businessTypeData.filter(ele => ele.value !== 'E');
            }
            // 交易所暂时不支持融资融券业务
            this.businessTypeData = this.businessTypeData.filter(ele => ele.value !== 'x');

            // this.innerOrderDirectionData[0]['innerDictionary'] = '[]'; // 测试数据为空情况
            this.innerOrderDirectionData.filter(ele => {
                if (ele.dictKey == this.instruction.businessType) {
                    if (ele['innerDictionary'] && JSON.stringify(ele['innerDictionary']) !== '{}') {
                        this.orderDirectionData = JSON.parse(ele['innerDictionary'] || '[]');
                    } else {
                        this.orderDirectionData = [];
                        this.instruction.orderDirection = '';
                    }
                    if (this.orderDirectionData.length && type) {
                        this.instruction.orderDirection = this.orderDirectionData[0].dictKey;
                        this.changeFlag = this.orderDirectionData[0].param2;
                        // this.instruction.orderDirection = this.detail.orderDirection || this.orderDirectionData[0].dictKey;
                    } else {
                        if (type) {
                            this.yh_message_warn('该业务类型无对应的委托方向');
                        }
                    }
                }
            });
        } else {
            this.businessTypeData = this.defaultStockBusinessTypes;
        }
    }
    /**
     * 重置表单数据
     */
    resetValues() {
        this.instruction.businessType = '1';
        this.instruction.orderDirection = '';
        this.instruction.reportCode = '';
        this.stockValues = {
            // businessType: '', // 业务类型
            orderPrice: '', // 指令价格
            orderAmount: '', // 指令数量
            orderBalance: '', // 指令金额
            winningRate: '', // 预估中签率
            orderPriceType: '2', // 价格模式
        };
        this.hkStock = false; // 是否港股股票
        this.buyStock = false; // 是否申购股票

        this.refinanceValues = {
            // 转融通指令额外表单数据
            // businessType: '', // 业务类型
            deadline: '', // 期限
            rate: '', // 费率
            orderAmount: '', // 融出数量
            opponentCode: '', // 交易对手
        };

        this.bondValues = {
            // 债券指令额外表单数据
            // businessType: '', // 业务类型
            netPrice: '', // 净价
            orderAmount: '', // 指令数量
            netMoney: '', // 指令金额
            allPrice: '', // 全价价格
            allAmount: '', // 全价数量
            allMoney: '', // 全价金额
            winningRate: '', // 预估中签率
            orderPriceType: '2', // 价格模式
        };
        this.buyBond = false; // 是否债券申购
        this.isNetPrice = false; // 是否净价

        this.fundValues = {
            // 基金指令额外表单数据
            // businessType: '', // 业务类型
            orderPrice: '', // 指令价格
            orderAmount: '', // 指令数量
            orderBalance: '', // 指令金额
            orderPriceType: '2', // 价格模式
        };
        this.warrantValues = {
            // 权证指令额外表单数据
            // businessType: '', // 业务类型
            orderPrice: '', // 指令价格
            orderAmount: '', // 指令数量
            orderBalance: '', // 指令金额
        };
        this.buyBackValues = {
            // 回购指令额外表单数据
            // businessType: '', // 业务类型
            orderBalance: '', // 指令金额
            orderRate: '',
            orderPriceType: '2', // 价格模式
        };
        this.form = {};
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-time/styles/order-form';

.form-row {
    margin-top: 3px;
    .el-form-item--small {
        margin: 0;
        & /deep/ .el-form-item__label {
            color: #575757;
        }
        & /deep/ .el-input__inner {
            height: 28px;
            line-height: 28px;
        }
    }
    .label-icon {
        border: 1.5px solid #595959;
        border-radius: 50%;
        line-height: 12px;
        font-size: 12px;
        display: inline-block;
        padding: 0 3px;
    }
    .popper {
        height: 80px;
    }
}
</style>
